package com.onec.service.channel.service.impl;

import com.onec.service.api.enums.ProductEnum;
import com.onec.service.api.enums.StatusEnum;
import com.onec.service.channel.dao.ChannelMerchantRepository;
import com.onec.service.channel.entity.ChannelInfo;
import com.onec.service.channel.entity.ChannelMerchant;
import com.onec.service.channel.service.ChannelMerchantService;
import io.netty.channel.ChannelException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author onec
 * @see
 * @since 20200821
 */
@Service
public class ChannelMerchantServiceImpl implements ChannelMerchantService {

    @Autowired
    ChannelMerchantRepository channelMerchantRepository;

    @Override
    public ChannelMerchant findByChannelIdProductMerchantNo(long channelId, String merchantNo, ProductEnum productEnum) {
        return channelMerchantRepository.findByChannelIdAndMerchantNoAndProduct(channelId, merchantNo, productEnum);
    }

    /**
     * 可用的渠道商户；
     *
     * @param channelId
     * @param merchantNo
     * @param productEnum
     * @return
     */
    @Override
    public ChannelMerchant getAvailableChannelIdProductMerchantNo(long channelId, String merchantNo, ProductEnum productEnum) {
        ChannelMerchant channelMerchant = this.findByChannelIdProductMerchantNo(channelId, merchantNo, productEnum);

        if (!Optional.ofNullable(channelMerchant).isPresent()) {
            throw new ChannelException();
        }
        if (StatusEnum.isSuccess(channelMerchant.getStatus())) {

        }
        if (StatusEnum.isFreeze(channelMerchant.getStatus())) {
            // 商户冻结：
        }
        return channelMerchant;
    }

    @Override
    public List<ChannelMerchant> getChannelMerchantProduct(String merchantNo, ProductEnum productEnum) {
        return channelMerchantRepository.findByMerchantNoAndProduct(merchantNo, productEnum);
    }

    @Override
    public ChannelMerchant createChannelMerchant(ChannelInfo channelInfo, String merchantNo, ProductEnum product) {
        ChannelMerchant channelMerchant = new ChannelMerchant();
        channelMerchant.setChannelId(channelInfo.getId());
        channelMerchant.setMerchantNo(merchantNo);
        channelMerchant.setVersion(1);
        channelMerchant.setProduct(product);

        channelMerchant.setStatus(StatusEnum.INIT);
        channelMerchant.setCreator("系统自建");
        return channelMerchantRepository.save(channelMerchant);
    }

    @Override
    public ChannelMerchant updateChannelMerchant(ChannelMerchant channelMerchant) {
        return channelMerchantRepository.save(channelMerchant);
    }

//    @Override
//    public ChannelMerchant updateChannelMerchantByChannel(ResponseMerchant responseMerchant) {
//
//
//        return null;
//    }


}
